package com.example.oscarchen.myapplication;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Chronometer;
import android.widget.TextView;

import com.example.oscarchen.myapplication.viewmodel.ChronometerViewModel;
import com.example.oscarchen.myapplication.viewmodel.LiveDataTimerViewModel;

/*
 * Copyright Withive, Inc. and/or its affiliates.
 * Created by Oscar.Chen on 11/16/2018
 * Email:  chanruida@outlook.com
 */
public class StartActivity extends AppCompatActivity {

    private LiveDataTimerViewModel mLiveDataTimerViewModel;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        int layout_id = R.layout.start_activity_5;

        setContentView(layout_id);

        switch (layout_id) {
            case R.layout.start_activity:
                chronometerTest();
                break;

            case R.layout.start_activity_3:
                mLiveDataTimerViewModel = ViewModelProviders.of(this).get(LiveDataTimerViewModel.class);
                subscribe();
                break;

            case R.layout.start_activity_5:
                break;

        }
    }

    private void subscribe() {
        final Observer<Long> elapsedTimeObserver = new Observer<Long>() {
            @Override
            public void onChanged(@Nullable Long aLong) {
                String newText = StartActivity.this.getResources().getString(
                        R.string.seconds, aLong);

                String newText2 = getResources().getString(R.string.seconds, aLong);

                ((TextView) findViewById(R.id.timer_textview)).setText(newText);

                Log.d("StartActivity", String.format("Updating timer %s %s", newText, newText2));
            }
        };

        mLiveDataTimerViewModel.getElapsedTime().observe(this, elapsedTimeObserver);
    }

    private void chronometerTest() {
        Chronometer chronometer = findViewById(R.id.chronometer);

        // The ViewModelStore provides a new ViewModel or one previously created.
        ChronometerViewModel chronometerViewModel
                = ViewModelProviders.of(this)
                .get(ChronometerViewModel.class);

        if (chronometerViewModel.getStartTime() == null) {
            long startTime = SystemClock.elapsedRealtime();
            chronometerViewModel.setStartTime(startTime);
            chronometer.setBase(startTime);
        } else {
            chronometer.setBase(chronometerViewModel.getStartTime());
        }

        chronometer.start();
    }
}